package com.yj.auto.core.web.system.controller;

import java.util.List;
import java.util.Map;

import org.quartz.Trigger;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.log.Log;
import com.xiaoleilu.hutool.util.NetUtil;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.annotation.Valid;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.web.system.model.Schedule;
import com.yj.auto.core.web.system.service.ScheduleService;
import com.yj.auto.helper.ScheduleHelper;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.utils.DateUtil;
import com.yj.auto.utils.QuartzUtil;

/**
 * 系统定时任务 管理
 * 
 * 描述：
 * 
 */
@Controller(viewPath = "system")
public class ScheduleController extends BaseController {
	private static final Log logger = Log.getLog(ScheduleController.class);

	private static final String RESOURCE_URI = "schedule/index";
	private static final String INDEX_PAGE = "schedule_index.html";
	private static final String FORM_PAGE = "schedule_form.html";
	private static final String SHOW_PAGE = "schedule_show.html";

	ScheduleService scheduleSrv = null;

	public void index() {
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		DataTables<Schedule> dt = getDataTable(query, scheduleSrv);
		List<Schedule> list = dt.getData();
		for (Schedule model : list) {
			initScheduleState(model);
		}
		renderJson(dt);
	}

	public void get() {
		Integer id = getParaToInt(0);
		Schedule model = scheduleSrv.get(id);
		initScheduleState(model);
		setAttr("model", model);
		render(SHOW_PAGE);
	}

	private void initScheduleState(Schedule model) {
		String next_time = "", prev_time = "";
		if (ScheduleHelper.isDisabled(model)) {
			model.setState(QuartzUtil.JOB_STATE_DISABLE);
		} else {
			model.setState(ScheduleHelper.jobState(model));
			Trigger trigger = ScheduleHelper.getTrigger(model);
			if (null != trigger) {
				next_time = DateUtil.toTimeStr(trigger.getNextFireTime());
				prev_time = DateUtil.toTimeStr(trigger.getPreviousFireTime());
			}
		}
		model.put("next_time", next_time);
		model.put("prev_time", prev_time);
	}

	public void form() {
		Integer id = getParaToInt(0);
		Schedule model = null;
		if (null != id && 0 != id) {
			model = scheduleSrv.get(id);
		} else {
			model = new Schedule();
			model.setSort(10);
			model.setState(QuartzUtil.JOB_STATE_NONE);
			model.setType(QuartzUtil.DEFAULT_JOB_GROUP);
		}
		setAttr("model", model);
		render(FORM_PAGE);
	}

	@Valid(type = Schedule.class)
	public boolean saveOrUpdate(Schedule model) {
		model.setLuser(getSuId());
		model.setLtime(Constants.NOW());
		boolean success = false;
		if (null == model.getId()) {
			if (null != scheduleSrv.getByCode(model.getCode())) {
				ResponseModel<String> res = new ResponseModel<String>(false);
				res.setMsg("任务代码[" + model.getCode() + "]已存在!");
				renderJson(res);
				return false;
			}
			success = scheduleSrv.save(model);
		} else {
			success = scheduleSrv.update(model);
		}
		ResponseModel<String> res = renderSaveOrUpdate(success, scheduleSrv);
		return res.isSuccess();
	}

	public boolean delete() {
		ResponseModel<String> res = _delete(scheduleSrv);
		return res.isSuccess();
	}

	public void control() {
		String action = getPara("action");
		Map<String, String[]> aa = getParaMap();
		Integer[] ids = getParaValuesToInt("ids[]");
		List<Schedule> list = scheduleSrv.getDao().findByColumn("id", ids);
		String oper = "";
		boolean success = true;
		try {
			if ("start".equals(action)) {// 启用
				oper = "启用";
				String serverIp = NetUtil.getLocalhostStr();
				for (Schedule s : list) {
					s.setServerIp(serverIp);
					s.setState(QuartzUtil.JOB_STATE_NONE);
					scheduleSrv.update(s);
				}
			} else if ("disable".equals(action)) {// 禁用
				oper = "禁用";
				for (Schedule s : list) {
					if (QuartzUtil.JOB_STATE_DISABLE.equals(s.getState())) {
						continue;
					}
					s.setState(QuartzUtil.JOB_STATE_DISABLE);
					scheduleSrv.update(s);
				}

			} else if ("pause".equals(action)) {// 暂停
				oper = "暂停";
				for (Schedule s : list) {
					ScheduleHelper.pauseJob(s);
				}
			} else if ("resume".equals(action)) {// 恢复
				oper = "恢复";
				for (Schedule s : list) {
					ScheduleHelper.resumeJob(s);
				}
			} else if ("run".equals(action)) {// 立即执行
				oper = "立即执行";
				for (Schedule s : list) {
					ScheduleHelper.startJob(s);
				}
			}
		} catch (Exception e) {
			logger.error("定时任务控制失败", e);
			success = false;
		}
		oper = oper + "定时任务";
		ResponseModel<String> res = new ResponseModel<String>(success);
		res.setMsg(success ? (oper + "成功") : (oper + "失败"));
		renderJson(res);
	}
}